package com.centling.smartSealForPhone.activity

import android.app.Activity
import android.bluetooth.BluetoothAdapter
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.graphics.Color
import android.os.Bundle
import android.text.Editable
import android.text.InputFilter
import android.text.TextUtils
import android.text.TextWatcher
import android.view.View
import com.centling.smartSealForPhone.BuildConfig
import com.centling.smartSealForPhone.R
import com.centling.smartSealForPhone.bean.LoginBean
import com.centling.smartSealForPhone.constants.GlobalData
import com.centling.smartSealForPhone.constants.SPConstants
import com.centling.smartSealForPhone.constants.UrlConstants
import com.wsdk.service.BluetoothLeService
import com.centling.smartSealForPhone.utils.*
import com.google.gson.Gson
import kotlinx.android.synthetic.main.activity_bug_report.*
import java.util.*

class BugReportActivity : TitleBarActivity(), BlueToothScanUtil.StopSearchListener {

    private var bugTypeId = ""

    private val bluetoothReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val action = intent.action

            if (BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED == action) {
                mProcessDialog.dismiss()
                if (BuildConfig.DEBUG) {
                    ShowToast.shortTime("Bug Report Connected")
                }
                GlobalData.isConnect = true
            } else if (BluetoothLeService.ACTION_DATA_AVAILABLE == action) {
                val data = intent.getByteArrayExtra(BluetoothLeService.EXTRA_DATA)
                if (ParseBluetoothData.isRepairMode(data)) {
                    //                    postSubmit();
                    LogUtil.d("Device has been set to repair mode.")
                    finish()
                } else if (ParseBluetoothData.isCloseRepairMode(data)) {
//                    postRevert()
                    LogUtil.d("Device has been set to work mode.")
                    finish()
                }
            }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_bug_report)
        setTitleBarText("故障报修")

        val intentFilter = IntentFilter()
        intentFilter.addAction(BluetoothLeService.ACTION_GATT_SERVICES_DISCOVERED)
        intentFilter.addAction(BluetoothLeService.ACTION_DATA_AVAILABLE)
        registerReceiver(bluetoothReceiver, intentFilter)

        val loginBean = Gson().fromJson(SPUtil.getString(SPConstants.LOGIN_JSON), LoginBean::class.java)
        macAddress = loginBean.equipRegisterInfo.blueToothMac
        sn = SPUtil.getString(SPConstants.CORE_SN)

        initView()
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(bluetoothReceiver)
    }

    fun initView() {
        bug_context.filters = arrayOf<InputFilter>(InputFilter.LengthFilter(300))

        bug_context.addTextChangedListener(TextLengthWatch(300))

        bug_context.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {

            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {

            }

            override fun afterTextChanged(s: Editable) {
                tv_number_limit.text = String.format(getString(R.string.number_limit_300), s.toString().length)
                if (s.toString().length == 300) {
                    tv_number_limit.setTextColor(Color.RED)
                } else {
                    tv_number_limit.setTextColor(Color.BLACK)
                }
            }
        })

        ll_bug_report_type.setOnClickListener {
            startActivityForResult(Intent(mContext, BugReportTypeActivity::class.java),
                    BUG_REPORT_TYPE)
        }

        btn_bug_submit.setOnClickListener(View.OnClickListener {
            if (!BlueToothScanUtil.isBlueToothOpened()) {
                val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(enableBtIntent, UNLOCK)
                return@OnClickListener
            }
            if (GlobalData.isConnect) {
                if ("0" == GlobalData.selfCheckStatus) {
                    LogUtil.d(GlobalData.isConnect.toString() + "")
                    postSubmit()
                } else {
                    ShowToast.shortTime("设备异常，请联系管理员! ")
                }
            } else {
                ShowDialog.showSelectDialog(mContext, "重新连接蓝牙", "蓝牙未连接，请先连接蓝牙", ""
                ) {
                    mProcessDialog.setTitle("正在连接蓝牙").showNormal()
                    blueToothScanUtil.setMacAddress(macAddress)
                    blueToothScanUtil.startSearchBlueDevice()
                    blueToothScanUtil.setStopSearchListener(
                            this@BugReportActivity)
                }
            }
        })
        btn_bug_revert.setOnClickListener(View.OnClickListener {
            if (!BlueToothScanUtil.isBlueToothOpened()) {
                val enableBtIntent = Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE)
                startActivityForResult(enableBtIntent, UNLOCK)
                return@OnClickListener
            }
            if (GlobalData.isConnect) {
                if ("0" == GlobalData.selfCheckStatus) {
                    LogUtil.d(GlobalData.isConnect.toString() + "")
                    postRevert()
                } else {
                    ShowToast.shortTime("设备异常，请联系管理员! ")
                }
            } else {
                ShowDialog.showSelectDialog(mContext, "重新连接蓝牙", "蓝牙未连接，请先连接蓝牙", ""
                ) {
                    mProcessDialog.setTitle("正在连接蓝牙").showNormal()
                    blueToothScanUtil.setMacAddress(macAddress)
                    blueToothScanUtil.startSearchBlueDevice()
                    blueToothScanUtil.setStopSearchListener(
                            this@BugReportActivity)
                }
            }
        })
    }

    private fun postSubmit() {
        val bugDetails = bug_context.text.toString()
        if (TextUtils.isEmpty(bugTypeId)) {
            ShowToast.shortTime("请选择故障类型")
            return
        }
        if (TextUtils.isEmpty(bugDetails)) {
            ShowToast.shortTime("故障描述不能为空")
            return
        }

        mProcessDialog.setTitle("正在设置维修模式").showNormal()
        val param = HashMap<String, String>()
        param["userId"] = SPUtil.getString(SPConstants.USER_ID)
        param["failureType"] = "1"
        param["selectFaultType"] = bugTypeId
        param["failureDescription"] = bugDetails
        postJsonEnqueue(UrlConstants.BUG_REPORT, param, object : OkHttpUtil.NetCallBack {
            override fun onSucceed(json: String) {
                mProcessDialog.dismiss()
                ShowToast.shortTime("设备故障报修成功")
                BluetoothLeService.disconnect()
                GlobalData.isInFixMode = false
                ControlUtil().repairMode()
            }

            override fun onFailed(reason: String) {
                mProcessDialog.dismiss()
                ShowToast.shortTime(reason)
            }
        })
    }

    private fun postRevert() {
        mProcessDialog.setTitle("正在撤销维修模式").showNormal()
        postJsonEnqueue(UrlConstants.BUG_REVERT, HashMap(1), object : OkHttpUtil.NetCallBack {
            override fun onSucceed(json: String) {
                mProcessDialog.dismiss()
                ShowToast.shortTime("撤销故障报修成功")
                GlobalData.isInFixMode = false
                ControlUtil().workMode()
            }

            override fun onFailed(reason: String) {
                mProcessDialog.dismiss()
                ShowToast.shortTime(reason)
            }
        })
    }

    override fun onStopped(timeout: Boolean) {
        mProcessDialog.dismiss()
        if (timeout) {
            ShowToast.shortTime("连接设备失败")
        }
    }

    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == UNLOCK && resultCode == Activity.RESULT_CANCELED) {
            finish()
        }
        if (requestCode == BUG_REPORT_TYPE && resultCode == Activity.RESULT_OK) {
            if (data != null) {
                bugTypeId = data.getStringExtra("which_bug_report_type_id")
                val reason = data.getStringExtra("which_bug_report_type_name")
                tv_bug_report_type.text = reason
                LogUtil.d("选择报修类型 $bugTypeId $reason")
            }
        }
    }

    companion object {
        private const val UNLOCK = 1992
        private const val BUG_REPORT_TYPE = 1993
    }
}
